package com.iddactylogram.server.transfer;

import com.iddactylogram.common.enumerate.CmdEnums;
import com.iddactylogram.server.transfer.handler.CmdHandler;
import com.iddactylogram.server.transfer.handler.HeartHandler;
import com.iddactylogram.server.transfer.handler.IdGenHandle;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class CmdHandlerMapping {
    private static final ConcurrentMap<CmdEnums, CmdHandler> CMD_HANDLER_MAPPING = new ConcurrentHashMap<>();

    private CmdHandlerMapping() {
        init();
    }

    private void init() {
        CMD_HANDLER_MAPPING.put(CmdEnums.ID_GEN, new IdGenHandle());
        CMD_HANDLER_MAPPING.put(CmdEnums.HEART, new HeartHandler());
    }

    public void addHandler(CmdEnums cmd, CmdHandler cmdHandler) {
        CMD_HANDLER_MAPPING.put(cmd, cmdHandler);
    }

    public CmdHandler getHandler(CmdEnums cmd) {
        return CMD_HANDLER_MAPPING.get(cmd);
    }

    public static class CmdHandlerMappingFactory {
        private static CmdHandlerMapping instance;

        public static CmdHandlerMapping getInstance() {
            if (instance == null) {
                synchronized (CmdHandlerMappingFactory.class) {
                    if (instance == null) {
                        instance = new CmdHandlerMapping();
                    }
                }
            }
            return instance;
        }
    }
}
